package com.fcgzs.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @Auther: ljj
 * @Description:   令牌解析，获取用户信息
 */
public class TokenDecode {


    //声明公钥路径
    public static final String KEY_PATH="public.key";


    private String getPublicKey(){
        ClassPathResource classPathResource = new ClassPathResource(KEY_PATH);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s;
            if ((s=bufferedReader.readLine())!=null) {
                return s;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //验签令牌
    private Map<String,String> dcodeToken(String token){
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(this.getPublicKey()));
        String claims = jwt.getClaims();//JSON 类型的字符串
        System.out.println(claims);
        return JSON.parseObject(claims,Map.class);
    }



    public Map<String,String> getUserInfo(){
        OAuth2AuthenticationDetails auth2AuthenticationDetails =(OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        //获取令牌信息
        //解析令牌
        return this.dcodeToken(auth2AuthenticationDetails.getTokenValue());

    }
}
